//
//  MYGChatTemplateListController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/20.
//

import UIKit

class MYGChatTemplateListController: MYGBaseController {
    private var contents: [MYGChatTemplateCellModel] = []
    private var stringContents: [MYGIMFastMessageModel]
    
    var sessionId: Int = 0
    init(contents: [MYGIMFastMessageModel]) {
        self.stringContents = contents
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        configItem()
        
        NotificationCenter.default.addObserver(self, selector: #selector(templateAdd), name: NSNotification.Name.init("MYGIMMessageTemplate"), object: nil)
    }
    
    @objc
    private func templateAdd(_ not: Notification) {
        guard let userInfo = not.userInfo as? [String: Any], let model = MYGIMFastMessageModel.deserialize(from: userInfo) else {
            return
        }
        
        if userInfo["action"] as? String == "delete" {
            stringContents.removeAll { item in
                item.id == model.id
            }
            
            configItem()
            return
        }
        
        if stringContents.contains(where: { item in
            item.id == model.id
        }) {
            let item = stringContents.first { item in
                item.id == model.id
            }
            item?.message_content = model.message_content
        } else {
            stringContents.append(model)
        }
        
        configItem()
    }
        
    private func configUI() {
        title = "添加消息"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: addButton)
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    private func configItem() {
        self.contents = stringContents.map({ str in
            let item = MYGChatTemplateCellModel()
            item.name = str.message_content
            item.editName = {[weak self] in
                guard let self = self else {
                    return
                }
                let alert = UIAlertController(title: "提示", message: "请输入模板内容", preferredStyle: .alert)
                alert.addTextField { tf in
                    tf.placeholder = "请输入模板内容"
                    tf.text = str.message_content
                }
                
                let okey = UIAlertAction(title: "确定", style: .default) { _ in
                    alert.dismiss(animated: true)
                    guard let text = alert.textFields?.first?.text, !text.isEmpty, text != str.message_content else {
                        return
                    }
                    
                    MYGSocketManager.shared.addTemplate(text, id: str.id, sessionId: self.sessionId, isAdd: false)
                }
                
                let cancel = UIAlertAction(title: "取消", style: .cancel)
                alert.addAction(okey)
                alert.addAction(cancel)
                
                self.present(alert, animated: true)
                
            }
            
            item.delete = {[weak self] in
                guard let self = self else {
                    return
                }
                
                MYGSocketManager.shared.deleteTemplate(id: str.id, sessionId: sessionId)
                
            }
            
            return item
        })
        
        tableView.reloadData()
    }
    
    private lazy var addButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("添加消息模板", for: .normal)
        btn.setTitleColor(.rgba(255, 9, 9, 1), for: .normal)
        btn.titleLabel?.font = .regular(13)
        btn.addTarget(self, action: #selector(add), for: .touchUpInside)
        return btn
    }()
    
    @objc
    private func add() {
        let alert = UIAlertController(title: "提示", message: "请输入模板内容", preferredStyle: .alert)
        alert.addTextField { tf in
            tf.placeholder = "请输入模板内容"
        }
        
        let okey = UIAlertAction(title: "确定", style: .default) { _ in
            alert.dismiss(animated: true)
            guard let text = alert.textFields?.first?.text, !text.isEmpty else {
                return
            }
            
            MYGSocketManager.shared.addTemplate(text, id: 0, sessionId: self.sessionId, isAdd: true)
        }
        
        let cancel = UIAlertAction(title: "取消", style: .cancel)
        alert.addAction(okey)
        alert.addAction(cancel)
        
        self.present(alert, animated: true)
    }
    
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.separatorStyle = .none
        tableV.delegate = self
        tableV.dataSource = self
        
        tableV.register(cellWithClass: MYGChatTemplateListCell.self)
        return tableV
    }()
}

extension MYGChatTemplateListController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        36
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGChatTemplateListCell.self, for: indexPath)
        cell.model = contents[indexPath.row]
        return cell
    }
}
